﻿using log4net;
using log4net.Appender;
using System;
using System.IO;
using System.Threading;
using System.Xml;

namespace LG_RECV_HEART
{
    /// <summary>
    /// 日志记录类
    /// </summary>
    /// <typeparam name="T">记录发生所在类</typeparam>
    /// <seealso cref="http://logging.apache.org/log4net"/>
    public sealed class Logger<T>
    {
        /// 日志文件过期时间(单位:天)，默认半年=180天
        private static int outdate_days = 60;
        private static readonly ILog log = LogManager.GetLogger(typeof(T));

        static Logger()
        {
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogSettings.config");
            if (File.Exists(configPath))
            {
                log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath));
            }
            #region 删除过期的日期文件
            Thread th = new Thread(() =>
            {
                try
                {
                    DeleteOutdatefiles(log, configPath);
                }
                catch (Exception ex)
                {
                }
            });
            th.IsBackground = true;
            th.Start();
            #endregion
        }

        /// <summary>
        /// 删除过期的日志文件
        /// </summary>
        private static void DeleteOutdatefiles(ILog log, string cfgfile)
        {
            if (log == null ||
                !log.IsInfoEnabled ||
                !log.IsErrorEnabled)
            {
                return;
            }
            try
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(cfgfile);
                var node = xdoc.SelectSingleNode("log4net");
                //附带属性到log4net.config，只能在根节点设置添加。
                //这个附带属性设置还不能放到其它节点，放到其它节点log4net解析会报错（虽未影响结果，但看着不舒服）
                if (null != node || node.Attributes != null || node.Attributes.Count > 0)
                {
                    outdate_days = 30;
                }
                var apps = log.Logger.Repository.GetAppenders();
                if (apps.Length <= 0)
                {
                    return;
                }
                var now = DateTime.Now;
                foreach (var item in apps)
                {
                    if (item is RollingFileAppender)
                    {
                        RollingFileAppender roll = item as RollingFileAppender;
                        var dir = Path.GetDirectoryName(roll.File);
                        var files = Directory.GetFiles(dir, "*.log");
                        var sample = "20181121-09.log";
                        foreach (var file in files)
                        {
                            var name = Path.GetFileName(file);
                            if (name.Length != sample.Length)
                            {
                                continue;
                            }
                            int year = int.Parse(name.Substring(0, 4));
                            int month = int.Parse(name.Substring(4, 2));
                            int day = int.Parse(name.Substring(6, 2));
                            var date = new DateTime(year, month, day);
                            TimeSpan ts = now - date;
                            if (ts.Days >= outdate_days)
                            {
                                File.Delete(file);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }

        }


        public static void Error(string message)
        {
            if (log.IsErrorEnabled)
                log.Error(message);
        }

        public static void Error(string message, Exception err)
        {
            if (log.IsErrorEnabled)
                log.Error(message, err);
        }

        public static void Debug(string message)
        {
            if (log.IsDebugEnabled)
                log.Debug(message);
        }

        public static void Info(string message)
        {
            if (log.IsInfoEnabled)
                log.Info(message);
        }
    }
}

